package com.whfc.fuum.service.impl;

import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.whfc.common.enums.*;
import com.whfc.common.exception.BizException;
import com.whfc.common.result.PageData;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.AssertUtil;
import com.whfc.common.util.PageUtil;
import com.whfc.entity.dto.Apply.rep.QueryEmpSysIdDto;
import com.whfc.entity.dto.msg.AppMsgToUserDTO;
import com.whfc.fuum.dao.*;
import com.whfc.fuum.dto.*;
import com.whfc.fuum.entity.*;
import com.whfc.fuum.manager.SysUserManager;
import com.whfc.fuum.param.*;
import com.whfc.fuum.redis.SysUserRedisDao;
import com.whfc.fuum.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description:
 * @author: xugcheng
 * @version: 1.0
 * @date: 2019/10/14 17:53
 */
@Slf4j
@DubboService(interfaceClass = SysUserService.class, version = "1.0.0")
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserManager sysUserManager;

    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    private SysRuleMapper sysRuleMapper;

    @Autowired
    private SysDeptUserMapper sysDeptUserMapper;

    @Autowired
    private SysEmpUserMapper sysEmpUserMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserCodeMapper sysUserCodeMapper;

    @Autowired
    private SysRoleRuleMapper sysRoleRuleMapper;

    @Autowired
    private SysUserRedisDao sysUserRedisDao;

    @Autowired
    WxUserMapper wxUserMapper;

    /**
     * 小程序游客默认角色ID
     */
    @NacosValue(value = "${mp.tourist.default.role}", autoRefreshed = true)
    private Integer mpDefaultRoleId;

    @Override
    public SysUser getUserByUsername(String username) {
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public List<AppMsgToUserDTO> getAvailableRecUsers(List<Integer> deptIds) throws BizException {
        return sysUserMapper.selectMsgRecAvailableUsers(deptIds);
    }

    @Override
    public List<SysUserDTO> getUsersByDeptId(Integer deptId) throws BizException {
        List<Integer> list = sysDeptMapper.selectDescendantDeptIdList(deptId);
        if (list == null) {
            return new ArrayList<>();
        }
        return sysUserMapper.selectUserByDeptId(list);
    }

    @Override
    public List<SysDeptRoleDTO> getUserDeptRoles(Integer userId, Integer deptId) {
        //获取用户的组织机构
        List<SysDept> list = sysDeptUserMapper.selectDeptListByUserId(userId, deptId);
        //获取组织机构对应的角色
        List<SysDeptRoleDTO> deptRoleList = new ArrayList<>();
        for (SysDept sysDept : list) {
            SysDeptRoleDTO sysDeptRoleDTO = new SysDeptRoleDTO();
            sysDeptRoleDTO.setDeptId(sysDept.getId());
            sysDeptRoleDTO.setDeptName(sysDept.getName());
            //获取角色
            List<SysRoleDTO> roleList = sysUserRoleMapper.selectRoleListByUserIdAndDeptId(userId, sysDept.getId());
            sysDeptRoleDTO.setRoleList(roleList);
            deptRoleList.add(sysDeptRoleDTO);
        }
        return deptRoleList;
    }

    @Override
    public void editDeptRoles(SysUserRoleEdit request) throws BizException {
        Integer userId = request.getUserId();
        Integer deptId = request.getDeptId();
        List<Integer> roleIds = request.getRoleIds();
        //删除当前机构下面所有用户角色
        sysUserRoleMapper.delUserRoles(deptId, userId);
        //重新绑定当前机构下面的所有用户角色
        sysUserRoleMapper.batchInsertUserRole(deptId, userId, roleIds);

        //删除用户组织机构ID缓存
        sysUserRedisDao.deleteUserDeptIds(userId);
        //删除用户权限缓存
        sysUserRedisDao.deleteUserRules(userId);
    }

    @Override
    public void addDeptRoles(SysUserDeptRolesAdd userDeptRolesAdd) {
        Integer userId = userDeptRolesAdd.getUserId();
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该用户不存在.");
        }
        List<Integer> deptIds = userDeptRolesAdd.getDeptIds();
        if (deptIds == null || deptIds.isEmpty()) {
            return;
        }
        //保存组织机构
        for (Integer deptId : deptIds) {
            sysDeptUserMapper.insertDeptUser(deptId, userId);
        }

        List<Integer> roleIds = userDeptRolesAdd.getRoleIds();
        if (roleIds == null || roleIds.isEmpty()) {
            return;
        }
        for (Integer deptId : deptIds) {
            //保存用户角色关联
            sysUserRoleMapper.batchInsertUserRole(deptId, userId, roleIds);
        }

        //删除用户组织机构ID缓存
        sysUserRedisDao.deleteUserDeptIds(userId);
        //删除用户权限缓存
        sysUserRedisDao.deleteUserRules(userId);
    }

    @Override
    public SysUser getUserByCode(String code) throws AuthenticationException {
        SysUserCodeDTO sysUserCode = sysUserCodeMapper.selectByCode(code);
        if (sysUserCode == null) {
            throw new AuthenticationException("code错误");
        }
        Integer expireFlag = sysUserCode.getExpireFlag();
        if (expireFlag.equals(ExpireFlag.EXPIRED.getValue())) {
            throw new AuthenticationException("code已使用");
        }

        Date expireTime = sysUserCode.getExpireTime();
        if (new Date().after(expireTime)) {
            throw new AuthenticationException("code已过期");
        }
        String username = sysUserCode.getUsername();
        return sysUserMapper.selectByUsername(username);
    }

    @Override
    public SysUser getUserByGuid(String guid) throws AuthenticationException {
        if (StringUtils.isBlank(guid)) {
            return null;
        }
        return sysUserMapper.getUserByGuid(guid);
    }

    @Override
    public PageData<SysUserDTO> list(SysUser loginUser, SysUserListParam sysUserParam) throws BizException {
        Integer pageNum = sysUserParam.getPageNum();
        Integer pageSize = sysUserParam.getPageSize();
        List<Integer> deptIds = new ArrayList<>();
        Integer deptId = sysUserParam.getDeptId();
        if (deptId != null) {
            deptIds.add(deptId);
        } else {
            if (!SysUserType.INNER.getValue().equals(loginUser.getType())) {
                //非内部账号，获取当前用户所属的组织机构以及子组织机构
                List<Integer> deptIdList = getAllDeptId(loginUser.getId());
                if (!deptIdList.isEmpty()) {
                    deptIds.addAll(deptIdList);
                }
            }
        }
        PageHelper.startPage(pageNum, pageSize);
        List<SysUserDTO> sysUserList = sysUserMapper.selectCustomerUsersByParam(deptIds, sysUserParam.getKeyword());
        PageHelper.clearPage();

        return PageUtil.pageData(PageInfo.of(sysUserList));
    }

    @Override
    public SysUserDTO queryUserById(Integer userId) throws BizException {
        SysUserDTO sysUserDTO = sysUserMapper.selectUserById(userId);
        if (sysUserDTO == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "账号不存在");
        }
        return sysUserDTO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDeptUser(SysDeptUserAdd deptUserAdd) {
        //根据用户名查找用户
        SysUser existUser = sysUserMapper.selectByUsername(deptUserAdd.getUsername());
        if (existUser != null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "已存在此用户，不可重复添加");
        }

        //根据用户手机号查找用户
        SysUser selectByPhone = sysUserMapper.selectByPhone(deptUserAdd.getPhone());
        if (selectByPhone != null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该手机号已存在");
        }
        Integer type = deptUserAdd.getType();
        Date expireTime = deptUserAdd.getExpireTime();
        if (SysUserType.EXPERIENCE.getValue().equals(type) && expireTime == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "体验账号必须设置截止日期");
        }
        //新增账号
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String encryptedPassword = new SimpleHash("MD5", deptUserAdd.getPassword(), salt).toString();

        SysUser sysUser = new SysUser();
        sysUser.setUsername(deptUserAdd.getUsername());
        sysUser.setNickname(deptUserAdd.getNickname());
        sysUser.setEmail(deptUserAdd.getEmail());
        sysUser.setPhone(deptUserAdd.getPhone());
        sysUser.setStatus(EnableState.ENABLED.getValue());

        sysUser.setType(type);
        sysUser.setUserType(deptUserAdd.getUserType());
        sysUser.setExpireTime(expireTime);

        sysUser.setPassword(encryptedPassword);
        sysUser.setSalt(salt);
        sysUser.setGuid(deptUserAdd.getGuid());
        sysUserMapper.insertSelective(sysUser);

        Integer userId = sysUser.getId();
        Integer deptId = deptUserAdd.getDeptId();

        //机构和账号关联
        sysDeptUserMapper.insertDeptUser(deptId, userId);

        //账号和角色关联
        List<Integer> roleIds = deptUserAdd.getRoleIds();
        sysUserRoleMapper.batchInsertUserRole(deptId, userId, roleIds);

        //删除用户组织机构ID缓存
        sysUserRedisDao.deleteUserDeptIds(userId);
        //删除用户权限缓存
        sysUserRedisDao.deleteUserRules(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addEmpUser(SysEmpUserAdd empUserAdd){
        if (empUserAdd.getSysDeptUser().getDeptId() == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "参数错误");
        }
        SysUser existUser = sysUserMapper.selectByUsername(empUserAdd.getSysDeptUser().getUsername());
        if (existUser == null) {
            this.addDeptUser(empUserAdd.getSysDeptUser());
        }
        existUser = sysUserMapper.selectByUsername(empUserAdd.getSysDeptUser().getUsername());
        SysEmpUser sysEmpUser = new SysEmpUser();
        BeanUtils.copyProperties(empUserAdd, sysEmpUser);
        sysEmpUser.setSysUserId(existUser.getId());
        sysEmpUser.setDelFlag(DelFlag.UNDELETE.getValue());
        sysEmpUser.setCreateTime(new Date());
        sysEmpUser.setUpdateTime(new Date());
        sysEmpUserMapper.insertSelective(sysEmpUser);

    }

    @Override
    public SysEmpUser getEmpUser(Integer empId){
        return sysEmpUserMapper.selectByAppEmpId(empId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editDeptUser(SysDeptUserEdit request) {
        SysUserEdit sysUserEdit = new SysUserEdit();
        Integer userId = request.getUserId();
        sysUserEdit.setUserId(userId);
        sysUserEdit.setUsername(request.getUsername());
        sysUserEdit.setNickname(request.getNickname());
        sysUserEdit.setPhone(request.getPhone());
        sysUserEdit.setEmail(request.getEmail());
        sysUserEdit.setType(request.getType());
        sysUserEdit.setExpireTime(request.getExpireTime());
        sysUserEdit.setUserType(request.getUserType());
        edit(sysUserEdit);
        Integer deptId = request.getDeptId();
        List<Integer> roleIds = request.getRoleIds();
        //删除当前机构下面所有用户角色
        sysUserRoleMapper.delUserRoles(deptId, userId);
        //重新绑定当前机构下面的所有用户角色
        sysUserRoleMapper.batchInsertUserRole(deptId, userId, roleIds);

        //删除用户组织机构ID缓存
        sysUserRedisDao.deleteUserDeptIds(userId);
        //删除用户权限缓存
        sysUserRedisDao.deleteUserRules(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void del(SysUser sysUser, Integer userId) {
        SysUser user = sysUserMapper.selectByPrimaryKey(userId);
        List<Integer> deptIds = sysDeptUserMapper.selectDeptIdByUserId(userId);
        if (deptIds != null && deptIds.size() > 0) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "请您先删除此账号关联组织机构");
        }
        if (user != null && user.getCanDelete() == 0) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该账号不可删除。");
        }
        //自己不能删除自己
        if (sysUser.getId().equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "自己不能删除自己");
        }

        //删除用户相关资源
        sysUserRoleMapper.deleteByUserId(userId);
        sysDeptUserMapper.deleteByUserId(userId);
        // 删除账号
        sysUserMapper.deleteLogicById(userId);

        //删除用户组织机构ID缓存
        sysUserRedisDao.deleteUserDeptIds(userId);
        //删除账号权限缓存
        sysUserRedisDao.deleteUserRules(userId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void edit(SysUserEdit sysUserEdit) {
        Integer userId = sysUserEdit.getUserId();
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(userId);
        if (sysUser == null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该用户不存在.");
        }
        //用户名不能重复
        SysUser existUser = sysUserMapper.selectByUsername(sysUserEdit.getUsername());
        if (existUser != null && !existUser.getId().equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "已存在同名账号");
        }

        //根据用户手机号查找用户
        SysUser selectByPhone = sysUserMapper.selectByPhone(sysUserEdit.getPhone());
        if (selectByPhone != null && !selectByPhone.getId().equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该手机号已存在");
        }
        //更新账号信息
        sysUser.setUsername(sysUserEdit.getUsername());
        sysUser.setNickname(sysUserEdit.getNickname());
        sysUser.setEmail(sysUserEdit.getEmail());
        sysUser.setPhone(sysUserEdit.getPhone());
        sysUser.setType(sysUserEdit.getType());
        sysUser.setExpireTime(sysUserEdit.getExpireTime());
        sysUser.setUserType(sysUserEdit.getUserType());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public void enable(Integer id, Integer status, Integer userId) throws BizException {
        if (id.equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "自己不能禁用自己");
        }
        sysUserMapper.updateStatusByUserId(id, status);
    }

    @Override
    public void updatePassword(SysUser sysUser, UpdatePasswordParam request) throws BizException {
        //验证旧密码
        String username = sysUser.getUsername();
        SysUser user = sysUserMapper.selectByUsername(username);
        if (user == null) {
            throw new AuthenticationException("用户不存在");
        }
        String password = new SimpleHash("MD5", request.getOldPassword(), user.getSalt()).toString();
        if (!password.equals(user.getPassword())) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "旧密码验证错误");
        }

        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String newPassword = new SimpleHash("MD5", request.getNewPassword(), salt).toString();
        sysUserMapper.updatePassword(salt, newPassword, sysUser.getId());
    }

    @Override
    public void resetPassword(SysResetPasswordParam request) throws BizException {
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String password = new SimpleHash("MD5", request.getPassword(), salt).toString();
        sysUserMapper.updatePassword(salt, password, request.getUserId());
    }

    @Override
    public List<SysRuleDTO> getUserRuleList(SysUser loginUser, Integer platform) throws BizException {
        Integer userId = loginUser.getId();
        List<SysRuleDTO> ruleDTOList = sysUserRedisDao.getUserRules(userId, platform);
        if (ruleDTOList == null || ruleDTOList.isEmpty()) {
            //内部账号(查看所有权限)
            if (SysUserType.INNER.getValue().equals(loginUser.getType())) {
                ruleDTOList = sysRuleMapper.selectAllRuleList(platform);
            }
            //客户账号,只能查看其角色范围内的权限
            if (SysUserType.CUSTOMER.getValue().equals(loginUser.getType())) {
                ruleDTOList = sysUserRoleMapper.selectRuleListByUserId(loginUser.getId(), platform, null);
            }
            //体验账号
            else if (SysUserType.EXPERIENCE.getValue().equals(loginUser.getType())) {
                List<SysRuleDTO> sysRuleDTOS = sysUserRoleMapper.selectRuleListByUserId(loginUser.getId(), platform, null);
                ruleDTOList = sysRuleDTOS.stream().
                        filter(sysRuleDTO -> !sysRuleDTO.getType().equals(SysRuleType.BUTTON.getValue()))
                        .collect(Collectors.toList());
            }
            if (ruleDTOList != null && ruleDTOList.size() > 0) {
                sysUserRedisDao.setUserRules(userId, platform, ruleDTOList);
            }
        }

        return ruleDTOList != null ? ruleDTOList : Collections.emptyList();
    }

    @Override
    public List<SysRuleDTO> getUserRuleListByDeptId(SysUser loginUser, Integer platform, Integer deptId) throws BizException {
        if (loginUser == null) {
            return sysRoleRuleMapper.selectRuleDTOByRoleId(mpDefaultRoleId, platform);
        }
        //内部账号(查看所有权限)
        if (SysUserType.INNER.getValue().equals(loginUser.getType())) {
            return sysRuleMapper.selectAllRuleList(platform);
        }
        //普通账号
        else if (SysUserType.CUSTOMER.getValue().equals(loginUser.getType())) {
            return getCustomerListAll(loginUser, platform, deptId);
        }
        //体验账号
        else if (SysUserType.EXPERIENCE.getValue().equals(loginUser.getType())) {
            List<SysRuleDTO> sysRuleDTOS = getCustomerListAll(loginUser, platform, deptId);
            SysDeptUser sysDeptUser = sysDeptUserMapper.selectDeptUserByUserId(loginUser.getId(), deptId);
            if (sysDeptUser != null
                    && JoinType.INVITE.value().equals(sysDeptUser.getJoinType())
            ) {
                return sysRuleDTOS.stream()
                        .filter(sysRuleDTO -> sysRuleDTO.getType().equals(SysRuleType.MODULE.getValue()))
                        .collect(Collectors.toList());
            }
            return sysRuleDTOS;
        }
        return Collections.emptyList();
    }

    // 获取普通账号的所有菜单 过滤 硬件中心 内部应用 系统设置 三个板块
    private List<SysRuleDTO> getCustomerListAll(SysUser loginUser, Integer platform, Integer deptId) {
        List<SysRuleDTO> allList = sysRuleMapper.selectAllRuleList(platform);
        allList = allList.stream().filter(
                s -> !("硬件中心".equals(s.getShortName()) || "系统设置".equals(s.getShortName()) || "内部应用".equals(s.getShortName())) && s.getStatus() == 1
        ).collect(Collectors.toList());
        List<SysRuleDTO> sysRuleDTOS = getRuleList(loginUser, platform, deptId);
        Map<Integer, SysRuleDTO> map = sysRuleDTOS.stream().collect(Collectors.toMap(SysRuleDTO::getRuleId, v -> v));
        for (SysRuleDTO sysRuleDTO : allList) {
            if (ObjectUtils.isEmpty(map.get(sysRuleDTO.getRuleId()))) {
                sysRuleDTO.setOpenStatus(1);
            }
        }
        return allList;
    }

    @Override
    public List<SysRuleDTO> getMpUserRuleList(WxUser loginUser, Integer platform) throws BizException {
        String phone = loginUser.getPhone();
        //在后台有账号，查询返回
        if (StringUtils.isNotEmpty(phone)) {
            SysUser sysUser = sysUserMapper.selectByPhone(phone);
            if (sysUser != null) {
                return getUserRuleList(sysUser, platform);
            }
        }
        //在后台没有账号，获取游客权限
        return sysRoleRuleMapper.selectRuleDTOByRoleId(mpDefaultRoleId, platform);
    }

    @Override
    public List<SysRuleDTO> getUserRuleList(Integer sysUserId, Integer platform) throws BizException {
        SysUser user = sysUserMapper.selectByPrimaryKey(sysUserId);
        if (user == null) {
            return Collections.emptyList();
        }
        return this.getUserRuleList(user, platform);
    }

    @Override
    public List<SysRuleDTO> getUserRuleList(Integer sysUserId, Integer platform, Integer deptId) throws BizException {
        SysUser user = sysUserMapper.selectByPrimaryKey(sysUserId);
        if (user == null) {
            return Collections.emptyList();
        }
        return this.getUserRuleListByDeptId(user, platform, deptId);
    }

    @Override
    public PageData<SysUserDTO> innerUserList(Integer pageNum, Integer pageSize, String keyword) throws BizException {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUserDTO> list = sysUserMapper.selectInnerUsers(keyword);
        return PageUtil.pageData(PageInfo.of(list));
    }

    @Override
    public void innerUserAdd(SysInnerUserAddParam request) throws BizException {
        //根据用户名查找用户
        SysUser existUser = sysUserMapper.selectByUsername(request.getUsername());
        if (existUser != null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "已存在同名账号");
        }
        //根据用户手机号查找用户
        SysUser selectByPhone = sysUserMapper.selectByPhone(request.getPhone());
        if (selectByPhone != null) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该手机号已存在");
        }
        //新增账号
        String salt = UUID.randomUUID().toString().replaceAll("-", "");
        String encryptedPassword = new SimpleHash("MD5", request.getPassword(), salt).toString();

        SysUser sysUser = new SysUser();
        sysUser.setUsername(request.getUsername());
        sysUser.setNickname(request.getNickname());
        sysUser.setPhone(request.getPhone());
        sysUser.setPassword(encryptedPassword);
        sysUser.setSalt(salt);
        sysUser.setType(SysUserType.INNER.getValue());
        sysUserMapper.insertSelective(sysUser);
    }

    @Override
    public void innerUserEdit(SysInnerUserEditParam request) throws BizException {
        Integer userId = request.getUserId();
        //用户名不能重复
        SysUser existUser = sysUserMapper.selectByUsername(request.getUsername());
        if (existUser != null && !existUser.getId().equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "已存在同名账号");
        }

        //根据用户手机号查找用户
        SysUser selectByPhone = sysUserMapper.selectByPhone(request.getPhone());
        if (selectByPhone != null && !selectByPhone.getId().equals(userId)) {
            throw new BizException(ResultEnum.PARAM_ERROR.getCode(), "该手机号已存在");
        }
        //更新账号信息
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setUsername(request.getUsername());
        sysUser.setNickname(request.getNickname());
        sysUser.setPhone(request.getPhone());
        sysUserMapper.updateByPrimaryKeySelective(sysUser);
    }

    @Override
    public SysUser getUserById(Integer userId) throws BizException {
        return sysUserMapper.selectByPrimaryKey(userId);
    }

    @Override
    public SysUser getUserByPhone(String phone) {
        return sysUserManager.getUserByPhone(phone);
    }

    /**
     * 获取用户所有的组织机构ID（包含组织机构的子组织机构）
     *
     * @param userId
     * @return
     */
    private List<Integer> getAllDeptId(Integer userId) {
        List<Integer> deptIdList = sysDeptUserMapper.selectDeptIdByUserId(userId);
        List<Integer> deptIds = new ArrayList<>(deptIdList);
        for (Integer deptId : deptIdList) {
            List<Integer> childrenDeptId = sysDeptMapper.selectDescendantDeptIdList(deptId);
            deptIds.addAll(childrenDeptId);
        }
        deptIds = deptIds.stream().distinct().collect(Collectors.toList());
        return deptIds;
    }

    /**
     * 查询普通用户/体验用户权限
     *
     * @param loginUser
     * @param platform
     * @param deptId
     * @return
     */
    private List<SysRuleDTO> getRuleList(SysUser loginUser, Integer platform, Integer deptId) {
        return sysUserRoleMapper.selectRuleListByUserId(loginUser.getId(), platform, deptId);
    }

    @Override
    public UserBaseDTO getUserBase(Integer deptId, Integer wxUserId, String phone) {

        SysDeptDTO dept = sysDeptMapper.selectById(deptId);
        AssertUtil.isTrue(dept == null, "项目信息不存在");
        UserBaseDTO res = new UserBaseDTO();
        WxUser wxUser = wxUserMapper.selectByPrimaryKey(wxUserId);
        if (wxUser != null){
            if (!StringUtils.isEmpty(wxUser.getAvatarUrl())){
                res.setAvatar(wxUser.getAvatarUrl());
            }
            res.setNickname(wxUser.getNickName());
        }
        res.setWxUserId(wxUserId);
        res.setPrjName(dept.getName());

        SysUser sysUser = getUserByPhone(phone);
        if (sysUser != null) {
            Integer userId = sysUser.getId();
            res.setUserId(userId);
            res.setPhone(sysUser.getPhone());
        }
        return res;
    }

    @Override
    public SysUser appMpLogin(int loginType, String phone, String username, String password, String cid) {
        log.info("appMpLogin loginType={},cid={}",loginType,cid);
        SysUser user = null;
        //手机号验证码登录
        if (3 == loginType) {
            user = this.getUserByPhone(phone);
            if (user == null) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "手机号码错误");
            }
            if (EnableState.DISABLED.getValue().equals(user.getStatus())) {
                throw new BizException(ResultEnum.FAILURE.getCode(), "账号已被禁用");
            }//账号密码登录
        } else if (4 == loginType) {
            user = this.getUserByUsername(username);
            if (user == null) {
                throw new AuthenticationException("账号或密码错误");
            }
            if (EnableState.DISABLED.getValue().equals(user.getStatus())) {
                throw new AuthenticationException("账号已被禁用");
            }
            String encryptedPassword = new SimpleHash("MD5", password, user.getSalt()).toString();
            if (!user.getPassword().equalsIgnoreCase(encryptedPassword)) {
                throw new AuthenticationException("账号或密码错误");
            }
            if (StringUtils.isNotBlank(cid)){
                user.setGuid(cid);
                int ret = sysUserMapper.updateByPrimaryKey(user);
                log.info("更新user cid {}", ret>0);
            }
        }
        return user;
    }

    @Override
    public SysEmpUser getEmpUserByEmpId(Integer empId){
        return sysEmpUserMapper.selectByAppEmpId(empId);
    }

    @Override
    public SysUser selectByPrimaryKey(Integer id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<String> selectNamePrimaryKey(List<String> ids) {
        return sysUserMapper.selectNamePrimaryKey(ids);
    }

    @Override
    public List<QueryEmpSysIdDto> getAppEmpIdList(List<String> empNames) {
        return sysUserMapper.getAppEmpIdList(empNames);
    }
    @Override
    public List<QueryEmpSysIdDto> getAppEmpEmpNamesIdList(List<String> ids) {
        return sysUserMapper.getAppEmpEmpNamesIdList(ids);
    }

    @Override
    public List<QueryEmpSysIdDto> getAppEmps(Integer empId,Integer deptId) {
        return sysUserMapper.getAppEmps(empId,deptId);
    }

    @Override
    public SysEmpUser getSysEmpUserByUserId(Integer userId) {
        return sysEmpUserMapper.getSysEmpUserByUserId(userId);
    }
}
